package cn.itcast.service.impl;

import cn.itcast.dao.AccountDao;
import cn.itcast.entity.Account;
import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

@Service
public class AccountServiceImpl implements AccountService{

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private TransactionTemplate transactionTemplate;

    // 如果没有用事务，数据库会添加一条记录；如果有应用事务成功，数据库无变化
    @Override
    public void save(Account account) {


        // 创建回调函数
        TransactionCallback<Object> callback = new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                /* 这里存放需要事务控制的代码*/
                accountDao.save(account);
                int i = 1/0;
                accountDao.save(account);
                return null;
            }
        };
        // 执行事务控制，传入回调函数
        transactionTemplate.execute(callback);
    }
}
